package com.aletto.general_store.presenters;

import android.content.Context;
import android.content.SharedPreferences;

import com.aletto.general_store.GeneralStoreApplication;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.presenters.NetLifecycleTask;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class SearchHistoryPresenter extends NetLifecycleTask<List<String>, INetTask.View<List<String>>> {
    private static final String KEY = "SEARCH_HISTORY";

    private List<String> mSearchHistoryList;

    private final SharedPreferences searchHistory;

    public SearchHistoryPresenter() {
        mSearchHistoryList = new ArrayList<>();

        searchHistory = GeneralStoreApplication.sInstance.getSharedPreferences(KEY, Context.MODE_PRIVATE);
    }

    public void findAll() {
        String string = searchHistory.getString(KEY, null);
        if (string != null) {
            mSearchHistoryList = new Gson().fromJson(string, new TypeToken<List<String>>() {
            }.getType());
            mView.success(mSearchHistoryList);
        }
    }

    public void add(CharSequence item) {
        if (item == null || item.length() <= 0) {
            return;
        }

        item = item.toString().trim();

        for (String historySearch : mSearchHistoryList) {
            if (item.equals(historySearch)) {
                return;
            }
        }

        if (mSearchHistoryList.size() >= 10) {
            mSearchHistoryList.remove(mSearchHistoryList.size() - 1);
        }

        mSearchHistoryList.add(0, item.toString());
        mView.success(mSearchHistoryList);
        searchHistory.edit().putString(KEY, new Gson().toJson(mSearchHistoryList)).apply();
    }

    public void remove(String item) {
        for (int index = 0; index < mSearchHistoryList.size(); index++) {
            if (item.equals(mSearchHistoryList.get(index))) {
                mSearchHistoryList.remove(index);
                break;
            }
        }

        mView.success(mSearchHistoryList);
        searchHistory.edit().putString(KEY, new Gson().toJson(mSearchHistoryList)).apply();
    }

    public void clear() {
        mSearchHistoryList.clear();
        mView.success(mSearchHistoryList);
        searchHistory.edit().remove(KEY).apply();
    }

}
